package com.mytech.cslive.dsp;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import android.media.MediaRecorder;

public class Controller {

	public interface DTMFRecieved {
		/**
		 * Method to implement when key is recieved
		 * 
		 * @param recievedSignal
		 *            The key decoded from sound
		 */
		void gotSignal(char recievedSignal);
	}
	private boolean started;

	private RecordTask recordTask;
	private RecognizerTask recognizerTask;
	BlockingQueue<DataBlock> blockingQueue;

	private Character lastValue;
	private DTMFRecieved recievedHandler;

	/**
	 * Default CTOR
	 */
	public Controller(DTMFRecieved handler) {
		//
		recievedHandler = handler;
		started = false;
	}

	public void toggleState(Boolean state) {
		if (state == true) {

			lastValue = ' ';

			blockingQueue = new LinkedBlockingQueue<DataBlock>();

			recordTask = new RecordTask(this, blockingQueue);

			recognizerTask = new RecognizerTask(this, blockingQueue);

			recordTask.execute();
			recognizerTask.execute();

			started = true;
		} else {

			recognizerTask.cancel(true);
			recordTask.cancel(true);

			started = false;
		}
	}

	public boolean isStarted() {
		return started;
	}

	public int getAudioSource() {
		// Can be other audio source, depends on situation and demand
		return MediaRecorder.AudioSource.MIC;
	}

	public void keyReady(char key) {

		if (key != ' ') {
			if (lastValue != key) {
				recievedHandler.gotSignal(key);
			}
		}
		lastValue = key;
	}
}
